
def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }


# sku序列化器
from apps.goods.models import SKU, SKUSpecification
from rest_framework import serializers
class SKUOptionId(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ('spec_id', 'option_id')


class SKUInfo(serializers.ModelSerializer):
    '''
                "id": "商品SKU ID",
                "name": "商品SKU名称",
                "spu": "商品SPU名称",
                "spu_id": "商品SPU ID",
                "caption": "商品副标题",
                "category_id": "三级分类id",
                "category": "三级分类名称",
                "price": "价格",
                "cost_price": "进价",
                "market_price": "市场价格",
                "stock": "库存",
                "sales": "销量",
                "is_launched": "上下架",
    '''
    spu_id = serializers.IntegerField()
    spu = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()
    category = serializers.StringRelatedField(read_only=True)
    specs = SKUOptionId(many=True)

    class Meta:
        model = SKU
        fields = '__all__'





# 定义序列化器
from rest_framework.serializers import Serializer, ModelSerializer
from apps.users.models import User


class UsersSerializers(ModelSerializer):


    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'password')
        read_only_fields = ('id',)  # 只参与序列化不参与反序列化的字段
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
                        },
            'password': {'max_length': 20,
                        'min_length': 8,
                        'write_only': True
                        }
        }

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user


# 定义商品序列化器
from apps.goods.models import SPUSpecification
from rest_framework import serializers
class GoodsSpecSerializer(ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    class Meta:
        model = SPUSpecification
        fields = '__all__'